/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.cn.xiaonuo.tcrfinance.tcrshops.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cn.xiaonuo.common.constant.Status;
import com.cn.xiaonuo.common.entity.BusinessMessage;
import com.cn.xiaonuo.common.utils.ExportExcelUtils;
import com.cn.xiaonuo.common.vo.ExcelData;
import com.cn.xiaonuo.core.exception.ServiceException;
import com.cn.xiaonuo.dbs.core.annotation.DataSource;
import com.cn.xiaonuo.tcrfinance.tcrorder.entity.PvPossessionGoods;
import com.cn.xiaonuo.tcrfinance.tcrorder.entity.PvTicketingRecord;
import com.cn.xiaonuo.tcrfinance.tcrorder.mapper.PvOrderMapper;
import com.cn.xiaonuo.tcrfinance.tcrorder.mapper.PvPossessionGoodsMapper;
import com.cn.xiaonuo.tcrfinance.tcrorder.mapper.PvTicketingRecordMapper;
import com.cn.xiaonuo.tcrfinance.tcrshops.entity.HpcProductResult;
import com.cn.xiaonuo.tcrfinance.tcrshops.entity.PvProduct;
import com.cn.xiaonuo.tcrfinance.tcrshops.entity.PvProductGl;
import com.cn.xiaonuo.tcrfinance.tcrshops.entity.SlGwjProduct;
import com.cn.xiaonuo.tcrfinance.tcrshops.enums.ProductTypeExceptionEnum;
import com.cn.xiaonuo.tcrfinance.tcrshops.mapper.PvOrderFormMapper;
import com.cn.xiaonuo.tcrfinance.tcrshops.mapper.PvProductGlMapper;
import com.cn.xiaonuo.tcrfinance.tcrshops.mapper.PvProductMapper;
import com.cn.xiaonuo.tcrfinance.tcrshops.mapper.SlGwjProductMapper;
import com.cn.xiaonuo.tcrfinance.tcrshops.param.*;
import com.cn.xiaonuo.tcrfinance.tcrshops.service.ProductService;
import com.cn.xiaonuo.tcrfinance.tcrshops.service.SlGwjProductService;
import com.cn.xiaonuo.tcrfinance.tcrshops.vo.ExportPickingRecordsVo;
import com.cn.xiaonuo.tcrfinance.tcrusers.entity.PvWallet;
import com.cn.xiaonuo.tcrfinance.tcrusers.mapper.PvWalletMapper;
import com.cn.xiaonuo.tcrfinance.tcrusers.param.MasterAccountExcelParam;
import com.cn.xiaonuo.tcrfinance.tcrusers.vo.NewMasterAccountExcelVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;


@Service
public class ProductServiceImpl extends ServiceImpl<PvProductMapper, PvProduct> implements ProductService {

    @Autowired
    private PvProductMapper pvProductMapper;
    @Autowired
    private PvProductGlMapper pvProductGlMapper;
    @Autowired
    private PvTicketingRecordMapper pvTicketingRecordMapper;
    @Autowired
    private PvOrderFormMapper pvOrderFormMapper;
    @Autowired
    private PvPossessionGoodsMapper pvPossessionGoodsMapper;
    @Autowired
    private PvWalletMapper pvWalletMapper;
    @Resource
    private SlGwjProductService slGwjProductService;
    @Autowired
    private PvOrderMapper pvOrderMapper;
    @Override
    public BusinessMessage updateProductXuNiVolume(PvProductParam pvProductParam) {
        PvProduct pvProduct = new PvProduct();
        BeanUtil.copyProperties(pvProductParam, pvProduct);//商品实体赋值
        BusinessMessage<Object> message = new BusinessMessage<>();
        PvProduct pvProduct1 = pvProductMapper.selectById(pvProduct.getId());
        pvProduct1.setSalesVolume(pvProduct.getSalesVolume() + pvProduct1.getSalesVolume());
        int i = pvProductMapper.updateById(pvProduct1);
        if (i != 1) {
            message.setMessage("更新商品数据失败");
            message.setCode("-1");
            message.setSuccess(false);
            return message;
        }
        message.setMessage("更新商品数据成功");
        message.setCode("200");
        message.setSuccess(true);
        return message;
    }

    @Override
    public BusinessMessage updateProductStatus(ProductReqParam productReqParam) {
        BusinessMessage<Object> message = new BusinessMessage<>();
        Integer productId = productReqParam.getProductId();
        Integer status = productReqParam.getStatus();
        PvProduct pvProduct = pvProductMapper.selectById(productId);
        pvProduct.setSoldOut(status);
        pvProduct.setUpdatedAt(new Date());
        if (status==3){
            pvProduct.setDel(1);
        }
        int i = pvProductMapper.updateById(pvProduct);
        // 同步修改sl_gwj_product表
        GwjProductReqParam param = new GwjProductReqParam();
        param.setId(pvProduct.getProductNumber());
        param.setStatus(status);
        slGwjProductService.updateGwjProductStatus(param);
        if (i == 1) {
            message.setCode("200");
            message.setSuccess(true);
            message.setMessage("操作成功");
            return message;
        }
        message.setCode("-1");
        message.setSuccess(false);
        message.setMessage("操作失败");
        return message;
    }

    /**
     * 查询商品上票信息
     */
    @Override
    public PvProductGl queryTicket(Integer productId) {
        PvProduct pvProduct = pvProductMapper.selectById(productId);
        LambdaQueryWrapper<PvProductGl> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PvProductGl::getShopId, pvProduct.getShopId());
        PvProductGl pvProductGl = pvProductGlMapper.selectOne(queryWrapper);
        return pvProductGl;
    }

    /**
     * 清空当日成交量
     *
     * @return
     */
    @Override
    public Integer clearVolume() {
        return pvProductMapper.clearVolume();
    }

    /**
     * @param pvProductParam
     * @return
     */
    @Override
    public PvProduct detail(PvProductParam pvProductParam) {
        PvProduct pvProduct = this.getById(pvProductParam.getId());
        if (ObjectUtil.isNull(pvProduct)) {
            throw new ServiceException(ProductTypeExceptionEnum.NOT_EXIST);
        }
        return pvProduct;
    }

    /**
     * 首页商品列表
     *
     * @return
     */
    @Override
    public BusinessMessage queryProductNameList(ProductReqParam productReqParam) {
        HpcProductResult productResult = new HpcProductResult();
        BeanUtil.copyProperties(productReqParam, productResult);
        BusinessMessage<Object> message = new BusinessMessage<>();
        // 设置分页参数
        List<HpcProductResult> lists = pvProductMapper.queryProductNameList(productResult);
        if (lists.size() > 0) {
            message.setCode("200");
            message.setData(lists);
            message.setSuccess(true);
            message.setMessage("操作成功");
            return message;
        }
        message.setMessage("没有查询数据");
        message.setCode("-1");
        message.setSuccess(false);
        return message;
    }

    /**
     * 查看商品类别
     */
    @Override
    public List<Map<String, Object>> queryProductNumByUserId(Integer productId, String productName, String accounts, String phone) {
        return pvProductMapper.queryProductNumByUserId(productId, productName, accounts, phone);
    }

    @Override
    public BusinessMessage updateSalesStatus(Integer productId, Integer isSale) {
        BusinessMessage message = new BusinessMessage();
        if (productId == null) {
            message.setCode(Status.failCode);
            message.setSuccess(false);
            message.setMessage("订单Id不能为空");
            return message;
        }
        if (isSale == null) {
            message.setCode(Status.failCode);
            message.setSuccess(false);
            message.setMessage("售卖状态不能为空");
            return message;
        }
        PvProduct pvProduct = pvProductMapper.selectById(productId);
        if (pvProduct != null) {
            if (pvProduct.getSalesModeId() == 2) {
                pvProduct.setProdStatus(isSale);
                LambdaQueryWrapper<PvProductGl> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(PvProductGl::getShopId, pvProduct.getShopId());
                PvProductGl pvProductGl = pvProductGlMapper.selectOne(wrapper);
                if (pvProductGl != null) {
                    pvProductGl.setProdStatus(isSale);
                    pvProductGlMapper.updateById(pvProductGl);
                    pvProductMapper.updateById(pvProduct);
                    message.setCode(Status.successCode);
                    message.setSuccess(true);
                    message.setMessage(Status.success);
                    return message;
                } else {
                    message.setCode(Status.failCode);
                    message.setSuccess(false);
                    message.setMessage("商品信息错误");
                    return message;
                }
            } else {
                message.setCode(Status.failCode);
                message.setSuccess(false);
                message.setMessage("非寄售商品不可更改售卖状态");
                return message;
            }
        } else {
            message.setCode(Status.failCode);
            message.setSuccess(false);
            message.setMessage("该商品不存在");
            return message;
        }
    }

    @Override
    public Page<PvTicketingRecord> ticketPage(TicketParam param) {
        if (ObjectUtils.isEmpty(param.getPageNo()) || param.getPageNo() < 1) {
            param.setPageNo(1);
        }
        if (ObjectUtils.isEmpty(param.getPageSize()) || param.getPageSize() < 1) {
            param.setPageSize(10);
        }
        QueryWrapper<PvTicketingRecord> wrapper = new QueryWrapper<>();
        wrapper.eq(ObjectUtils.isNotEmpty(param.getProductId()), "product_id", param.getProductId());
        wrapper.like(ObjectUtils.isNotEmpty(param.getProductName()), "product_name", param.getProductName());
        wrapper.eq(ObjectUtils.isNotEmpty(param.getShopId()), "shop_id", param.getShopId());
        wrapper.ge(ObjectUtils.isNotEmpty(param.getCreateBeginTime()), "create_time", param.getCreateBeginTime());
        wrapper.le(ObjectUtils.isNotEmpty(param.getCreateEndTime()), "create_time", param.getCreateEndTime());
        wrapper.orderByDesc("create_time");
        Page<PvTicketingRecord> pvTicketingRecordPage = pvTicketingRecordMapper.selectPage(new Page<>(param.getPageNo(), param.getPageSize()), wrapper);

        return pvTicketingRecordPage;
    }

    @Override
    public BusinessMessage queryHpcHtProductList(HtProductListParam param) {
        BusinessMessage<Object> message = new BusinessMessage<>();
        if (ObjectUtils.isEmpty(param.getPickProductId())) {
            message.setSuccess(false);
            message.setMessage("商品不能为空");
            message.setCode("-1");
            return message;
        }
        List<String> pickProductIdList = null;
        if (StringUtils.isNotBlank(param.getPickProductId())) {
            String[] pickProductIds = param.getPickProductId().split(",");
            pickProductIdList = Arrays.asList(pickProductIds);
        }
        Map<String, Object> map=new HashMap<>();
        // 设置分页参数
        PageHelper.startPage(param.getPageNo(), param.getPageSize());
        List<Map<String, Object>> lists = pvProductMapper.queryHtProductList(pickProductIdList);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(lists);
        //未摘单数量
        List<Map<String, Object>> countlist = pvProductMapper.queryEntrustListCount("2", pickProductIdList);
        List<Object> entrustListCount = new ArrayList<>();
            for (String productId:pickProductIdList){
                Integer value = Integer.valueOf(productId);
                BusinessMessage count = this.queryHpcEntrustListCount(value);
                entrustListCount.add(count.getData());
            }
        if (lists.size() > 0) {
            map.put("pageInfo",pageInfo);
            map.put("countlist",countlist);
            map.put("entrustListCount",entrustListCount);
            message.setCode("200");
            message.setData(map);
            message.setSuccess(true);
            message.setMessage("操作成功");
            return message;
        }
        message.setMessage("没有查询数据");
        message.setCode("-1");
        message.setSuccess(false);
        return message;
    }

    @Override
    public void exportPickingRecords(HttpServletResponse response, MasterAccountExcelParam param) {
        if (ObjectUtils.isEmpty(param.getStartTime())){
            return;
        }
       List<ExportPickingRecordsVo> vos= pvOrderMapper.exportPickingRecords(param);
       try {
           List<List<Object>> rows = new ArrayList();
           ExcelData data = new ExcelData();
           data.setName("促销商品摘单记录数据导出");//sheet表名称
           //表头
           List<String> titles = new ArrayList();
           titles.add("商家名称");
           titles.add("账号");
           titles.add("平台服务费");
           titles.add("仓储费");
           titles.add("购物券");
           titles.add("商品奖励");
           data.setTitles(titles);
           for (ExportPickingRecordsVo vo : vos) {
               List<Object> row1 = new ArrayList();
               row1.add(vo.getShopName());
               row1.add(vo.getAccounts());
               row1.add(vo.getPlatformFwf());
               row1.add(vo.getStorageFwf());
               row1.add(vo.getGwq());
               row1.add(vo.getProductReward());
               rows.add(row1);
           }
           data.setRows(rows);
           ExportExcelUtils.exportExcel(response, "促销商品摘单记录数据导出.xlsx", data);
       }catch (Exception e){
           e.printStackTrace();
       }

    }

    public BusinessMessage queryHpcEntrustListCount(Integer productId) {
        BusinessMessage message = new BusinessMessage();
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("productId", productId);
        PvProduct pvProduct = pvProductMapper.selectById(productId);
        PvProductGl pvProductGl = pvProductGlMapper.selectOne(new QueryWrapper<>(new PvProductGl() {{
            setShopId(pvProduct.getShopId());
        }}));
        if (ObjectUtils.isNotEmpty(pvProductGl)){
            Integer transferNum = pvOrderFormMapper.getTransferNum(productId, pvProductGl.getSellUserId());
            returnMap.put("transferNum", transferNum);
            PvPossessionGoods pvPossessionGoods = pvPossessionGoodsMapper.selectOne(new QueryWrapper<>(new PvPossessionGoods() {{
                setUserId(pvProductGl.getSellUserId());
                setProductId(productId);
            }}));
            if (ObjectUtils.isNotEmpty(pvPossessionGoods)){
                returnMap.put("cansellNumber",pvPossessionGoods.getCansellNumber());
            }else {
                returnMap.put("cansellNumber",0);
            }
            //乡村振兴总账户余额
            PvWallet pvWallet = pvWalletMapper.selectOne(new QueryWrapper<>(new PvWallet() {{
                setUserId(pvProductGl.getSellUserId());
            }}));
            BigDecimal availableBalance = new BigDecimal(0);
            if (pvWallet != null) {
                availableBalance = pvWallet.getAvailableBalance();
            }
            returnMap.put("totalAccountBalance", availableBalance);
        }else {
            returnMap.put("transferNum",0);
            returnMap.put("cansellNumber",0);
            returnMap.put("totalAccountBalance",0);
        }

        message.setMessage("查询成功");
        message.setSuccess(true);
        message.setCode("200");
        message.setData(returnMap);
        return message;
    }

}
